package com.ocom.payconfig.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.emqx.EntityYhMqtt0607;
import com.ocom.common.entity.pay.EntityXfRecordProcessExtend;
import com.ocom.common.entity.payconfig.EntityMqttDevice;
import com.ocom.common.entity.payconfig.EntityMqttOperation;
import com.ocom.common.entity.payconfig.EntityMqttOperationProcess;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.emqx.*;
import com.ocom.common.request.payconfig.*;
import com.ocom.common.request.payhandle.GetDeviceInfoRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.emqx.GetDeviceArgsVo;
import com.ocom.common.vo.emqx.YhDeviceWorkStatusVo;
import com.ocom.common.vo.payconfig.DeviceInfoVo;
import com.ocom.common.vo.payconfig.GetDishesPriceInfoListVo;
import com.ocom.payconfig.client.EmqxClientService;
import com.ocom.payconfig.client.PayhandleClientService;
import com.ocom.payconfig.client.XfRecordFeign;
import com.ocom.payconfig.service.MqttDeviceService;
import com.ocom.payconfig.service.MqttOperationService;
import com.ocom.payconfig.service.XfRecordProcessExtendService;
import com.ocom.payconfig.service.XfRecordProcessService;
import com.ocom.redis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
public class MqttDeviceController {
    private final Logger log = LoggerFactory.getLogger(MqttDeviceController.class);
    @Autowired
    private MqttDeviceService mqttDeviceService;

    @Autowired
    private MqttOperationService mqttOperationService;

    @Autowired
    private PayhandleClientService payhandleClientService;


    @Autowired
    private XfRecordProcessExtendService xfRecordProcessExtendService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Autowired
    private EmqxClientService emqxClientService;

    @PostMapping(PayConfigUrl.URL_getMqttDevice)
    public Result getMqttDevice(@RequestBody GetMqttDeviceRequest request){
        GetDeviceInfoRequest getDeviceInfoRequest = new GetDeviceInfoRequest();
        getDeviceInfoRequest.setMachNo(request.getMachNo());
        getDeviceInfoRequest.setComId(request.getComId());
        DeviceInfoVo getDeviceInfoVo = this.getDeviceInfo(getDeviceInfoRequest);
//         = result.getData();
//        log.info("获取物联网设备列表_log1：{}，{}",JSON.toJSONString(request),JSON.toJSONString(getDeviceInfoVo));
        if(ObjectUtil.isEmpty(getDeviceInfoVo)){
            return ResultUtil.success();
        }

        if(ObjectUtil.isEmpty(getDeviceInfoVo.getMerchId())){
            return ResultUtil.error(ResultEnum.Err_2031);
        }
        GetDeviceArgsRequest getDeviceArgsRequest = new GetDeviceArgsRequest();
        getDeviceArgsRequest.setComId(request.getComId());
        getDeviceArgsRequest.setMerchId(getDeviceInfoVo.getMerchId().intValue());
        getDeviceArgsRequest.setPointId(getDeviceInfoVo.getPointId());
        List<EntityMqttDevice> entityMqttDevices = this.mqttDeviceService.getDeviceArgs(getDeviceArgsRequest);
//        log.info("获取物联网设备列表_log2：{}",JSON.toJSONString(entityMqttDevices));
        List<GetDeviceArgsVo> getDeviceArgsVoList = new ArrayList<>();
        for (EntityMqttDevice entityMqttDevice:entityMqttDevices){
            entityMqttDevice.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo().trim());
            GetDeviceArgsVo getDeviceArgsVo = Convert.convert(GetDeviceArgsVo.class,entityMqttDevice);
            List<GetDishesPriceInfoListVo> listVoList = new ArrayList<>();
            if(ObjectUtil.isNotEmpty(entityMqttDevice.getDishesList())){
                for (Map.Entry<String,GetDishesPriceInfoListVo> getDishesPriceInfoListVoEntry: entityMqttDevice.getDishesList().entrySet()){
                    GetDishesPriceInfoListVo.Price price = new GetDishesPriceInfoListVo.Price();
                    price.setDishesPrice(getDishesPriceInfoListVoEntry.getValue().getPrice());
                    price.setPriceMode(getDishesPriceInfoListVoEntry.getValue().getPriceMode());
                    getDishesPriceInfoListVoEntry.getValue().setPriceList(Lists.newArrayList(price));
                    listVoList.add(getDishesPriceInfoListVoEntry.getValue());
                }
            }

            getDeviceArgsVo.setDishesList(listVoList);
            getDeviceArgsVoList.add(getDeviceArgsVo);
        }
//        log.info("获取物联网设备列表_log3：{}",JSON.toJSONString(getDeviceArgsVoList));
        return ResultUtil.success(getDeviceArgsVoList);
    }

    @PostMapping(PayConfigUrl.URL_newMqttOrder)
    public Result newMqttOrder(@RequestBody NewMqttOrderRequest request){
        EntityMqttDevice entityMqttDevice = Convert.convert(EntityMqttDevice.class,request);
        entityMqttDevice = this.mqttDeviceService.selectDevice(request.getComId(),entityMqttDevice);
        if(ObjectUtil.isEmpty(entityMqttDevice)){
            return ResultUtil.error(ResultEnum.Err_6002);
        }

        if(!entityMqttDevice.getOrderStatus().equals(0) || !entityMqttDevice.getErrStatus().equals(0)){
            log.info("下单异常_1:设备参数：【{}】",JSON.toJSONString(entityMqttDevice));
            return ResultUtil.error(ResultEnum.Err_6003);
        }

        if(!entityMqttDevice.getOnline()){
            return ResultUtil.error(ResultEnum.Err_6008);
        }

        YhDeviceWorkStatusRequest deviceWorkStatusRequest = new YhDeviceWorkStatusRequest();
        deviceWorkStatusRequest.setStatus(entityMqttDevice.getDeviceStatus());
        deviceWorkStatusRequest.setSubRun(entityMqttDevice.getSubRun());
        deviceWorkStatusRequest.setSubNum(entityMqttDevice.getSubNum());

        Result<YhDeviceWorkStatusVo> resultA= this.emqxClientService.yhDeviceWorkStatus(deviceWorkStatusRequest);
        YhDeviceWorkStatusVo yhDeviceWorkStatusVo = resultA.getData();
        log.info("设备下单,判断设备状态参数：【{}】，【{}】",JSON.toJSONString(deviceWorkStatusRequest),JSON.toJSONString(yhDeviceWorkStatusVo));
        if(yhDeviceWorkStatusVo.getRunState().equals(1)){
            log.info("下单异常:设备参数_2：【{}】,状态码参数：【{}】",JSON.toJSONString(entityMqttDevice),JSON.toJSONString(yhDeviceWorkStatusVo));
            return ResultUtil.error(ResultEnum.Err_6003);
        }

        entityMqttDevice.setOrderStatus(1);
        entityMqttDevice.setOrderTime(new Date());

        //获取最大orderId
        Integer maxId = this.mqttOperationService.getMaxOrderId(entityMqttDevice.getComId());
        entityMqttDevice.setOrderId(maxId + 1);
        this.mqttDeviceService.update(entityMqttDevice.getComId(),entityMqttDevice);
        GetDeviceInfoRequest getDeviceInfoRequest = new GetDeviceInfoRequest();
        getDeviceInfoRequest.setMachNo(request.getMachNo());
        getDeviceInfoRequest.setComId(request.getComId());
        DeviceInfoVo getDeviceInfoVo  = this.getDeviceInfo(getDeviceInfoRequest);
//        DeviceInfoVo getDeviceInfoVo = result.getData();

        this.redisUtil.hmSet("MqttXfDevice:" + entityMqttDevice.getMqttDeviceNo(), "orderStatus",entityMqttDevice.getOrderStatus());

        EntityMqttOperationProcess entityMqttOperationProcess = new EntityMqttOperationProcess();
        entityMqttOperationProcess.setComId(request.getComId());
        if(ObjectUtil.isNotEmpty(getDeviceInfoVo)){
            entityMqttOperationProcess.setMerchId(getDeviceInfoVo.getMerchId());
            entityMqttOperationProcess.setMerchName(getDeviceInfoVo.getMerchName());
            entityMqttOperationProcess.setPointId(getDeviceInfoVo.getPointId().longValue());
            entityMqttOperationProcess.setPointName(getDeviceInfoVo.getPointName());
            entityMqttOperationProcess.setDeviceName(getDeviceInfoVo.getDeviceName());
        }


        entityMqttOperationProcess.setPId(request.getPId());
        entityMqttOperationProcess.setOrderId(entityMqttDevice.getOrderId());
        entityMqttOperationProcess.setDeviceNo(request.getMachNo());

        entityMqttOperationProcess.setOrderPsw(intToHexWithFillZero(entityMqttDevice.getOrderId(),4));
        entityMqttOperationProcess.setMqttDeviceId(entityMqttDevice.getMqttDeviceId());
        entityMqttOperationProcess.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo());
        entityMqttOperationProcess.setMqttDeviceName(entityMqttDevice.getMqttDeviceName());
        entityMqttOperationProcess.setMqttDeviceType(entityMqttDevice.getMqttDeviceType());
        entityMqttOperationProcess.setMqttDeviceModel(entityMqttDevice.getMqttDeviceModel());
        entityMqttOperationProcess.setMqttDeviceSub(0L);
        entityMqttOperationProcess.setOrderNo(request.getTradeNo());
        entityMqttOperationProcess.setState(11);
        entityMqttOperationProcess.setOperateCode(request.getOperateCode());
        entityMqttOperationProcess.setPrice(request.getPrice());
        this.mqttOperationService.save(request.getComId(), entityMqttOperationProcess);
        return ResultUtil.success(entityMqttDevice);
    }

    @PostMapping(PayConfigUrl.URL_payMqttOrder)
    public Result payMqttOrder(@RequestBody PayMqttOrderRequest request) throws InterruptedException {
        EntityMqttOperationProcess entityMqttOperationProcess = Convert.convert(EntityMqttOperationProcess.class,request);
        entityMqttOperationProcess.setComId(request.getCompanyId());
        entityMqttOperationProcess = this.mqttOperationService.selectMqttProcess(request.getCompanyId(),entityMqttOperationProcess,Lists.newArrayList(11,13));
        Map<String,Integer> resultmMap = new HashMap<>();
        if(ObjectUtil.isEmpty(entityMqttOperationProcess)){
            log.info("log_1：订单异常{}",JSON.toJSONString(entityMqttOperationProcess));
            resultmMap.put("runState",2);
            return ResultUtil.success(resultmMap);
//            return ResultUtil.error(ResultEnum.Err_6004);
        }

        if(!entityMqttOperationProcess.getOrderNo().equals(request.getTradeNo())){
            resultmMap.put("runState",2);
            return ResultUtil.success(resultmMap);
//            return ResultUtil.error(ResultEnum.Err_6004);
        }

        EntityMqttDevice entityMqttDevice = new EntityMqttDevice();
        entityMqttDevice.setMqttDeviceId(request.getMqttDeviceId());
        entityMqttDevice.setComId(request.getCompanyId());
        entityMqttDevice = this.mqttDeviceService.selectDevice(request.getCompanyId(),entityMqttDevice);
        if(ObjectUtil.isEmpty(entityMqttDevice)){
            resultmMap.put("runState",2);
            return ResultUtil.success(resultmMap);
//            return ResultUtil.error(ResultEnum.Err_6004);
        }
        entityMqttDevice.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo().trim());
        //首次调用
        if(entityMqttOperationProcess.getState().equals(11)){
            if(request.getPId() > 0){
                entityMqttOperationProcess.setPId(request.getPId());
            }
            entityMqttOperationProcess.setPayTime(new Date());
            this.mqttOperationService.update(request.getCompanyId(),entityMqttOperationProcess);

            if(entityMqttDevice.getOrderStatus().equals(0) || !entityMqttDevice.getErrStatus().equals(0)){
                log.info("log_1:设备异常:【{}】",JSON.toJSONString(entityMqttDevice));
                resultmMap.put("runState",3);
                return ResultUtil.success(resultmMap);
//                return ResultUtil.error(ResultEnum.Err_6005);
            }
            YhDeviceWorkStatusRequest deviceWorkStatusRequest = new YhDeviceWorkStatusRequest();
            deviceWorkStatusRequest.setStatus(entityMqttDevice.getDeviceStatus());
            deviceWorkStatusRequest.setSubRun(entityMqttDevice.getSubRun());
            deviceWorkStatusRequest.setSubNum(entityMqttDevice.getSubNum());
            Result<YhDeviceWorkStatusVo> resultA= this.emqxClientService.yhDeviceWorkStatus(deviceWorkStatusRequest);
            if(!resultA.getCode().equals(200)){
                log.info("log_2:设备异常:【{}】",JSON.toJSONString(resultA));
                resultmMap.put("runState",3);
                return ResultUtil.success(resultmMap);
//                return  ResultUtil.error(ResultEnum.Err_6005);
            }

            YhDeviceWorkStatusVo deviceWorkStatus = resultA.getData();
            if(deviceWorkStatus.getOrdered().equals(1) || deviceWorkStatus.getRunState().equals(1)){
                log.info("log_3:设备异常:【{}】",JSON.toJSONString(deviceWorkStatus));
                resultmMap.put("runState",3);
                return ResultUtil.success(resultmMap);
//                return ResultUtil.error(ResultEnum.Err_6005);
            }else{
                RefreshMqttOrderStatusRequest refreshMqttOrderStatusRequest = new RefreshMqttOrderStatusRequest();
                refreshMqttOrderStatusRequest.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo());
                refreshMqttOrderStatusRequest.setComId(entityMqttDevice.getComId());
                refreshMqttOrderStatusRequest.setNewStatus(2);
                this.refreshMqttOrderStatus(refreshMqttOrderStatusRequest);
                log.info("log_4：更新订单信息:【{}】", JSON.toJSONString(refreshMqttOrderStatusRequest));
            }

        }

        if(entityMqttOperationProcess.getState().equals(13)){
            YhDeviceWorkStatusRequest deviceWorkStatusRequest = new YhDeviceWorkStatusRequest();
            deviceWorkStatusRequest.setStatus(entityMqttDevice.getDeviceStatus());
            deviceWorkStatusRequest.setSubRun(entityMqttDevice.getSubRun());
            deviceWorkStatusRequest.setSubNum(entityMqttDevice.getSubNum());
            Result<YhDeviceWorkStatusVo> resultA= this.emqxClientService.yhDeviceWorkStatus(deviceWorkStatusRequest);
            if(!resultA.getCode().equals(200)){
                resultmMap.put("runState",3);
                return ResultUtil.success(resultmMap);
//                return  ResultUtil.error(ResultEnum.Err_6005);
            }
            YhDeviceWorkStatusVo deviceWorkStatus = resultA.getData();
            if(deviceWorkStatus.getOrdered().equals(1) || deviceWorkStatus.getRunState().equals(1)){
                entityMqttOperationProcess.setState(31);
                this.mqttOperationService.update(entityMqttOperationProcess.getComId(),entityMqttOperationProcess);
                if(deviceWorkStatus.getOrdered().equals(0)){
                    log.info("log2_更新订单状态:【{}】",JSON.toJSONString(entityMqttOperationProcess));
                    resultmMap.put("runState",0);
                    return ResultUtil.success(resultmMap);
//                    return ResultUtil.success();
                }else{
                    log.info("log3_更新订单状态:【{}】",JSON.toJSONString(entityMqttOperationProcess));
                    resultmMap.put("runState",3);
                    return ResultUtil.success(resultmMap);
//                    return ResultUtil.error(ResultEnum.Err_6005);
                }
            }
        }

        //准备发06命令
        Integer status8A = null;
        Integer status87 = null;
        if(entityMqttDevice.getMqttDeviceType().equals(1)){
            log.info("发送洗衣机06指令");
            YhMqtt0607Request yhMqtt0607Request = new YhMqtt0607Request();
            yhMqtt0607Request.setDeviceNo(entityMqttDevice.getMqttDeviceNo());
            yhMqtt0607Request.setOrderNo(entityMqttOperationProcess.getOrderId().longValue());
//            yhMqtt0607Request.setLaundryModel(Integer.parseInt(entityMqttOperationProcess.getOperateCode()));
            yhMqtt0607Request.setLaundryModel(getInt(entityMqttOperationProcess.getOperateCode()));
            for (int i=0;i<50;i++){
                status8A = (Integer) this.redisUtil.get("YH_"+ entityMqttDevice.getMqttDeviceNo() + "_run_8A");
                if(ObjectUtil.isNotEmpty(status8A)){
                    break;
                }
                status87 = (Integer) this.redisUtil.get("YH_"+entityMqttDevice.getMqttDeviceNo()+"_"+entityMqttOperationProcess.getOrderId()+"_87");
                if(ObjectUtil.isNotEmpty(status87)){
                    break;
                }
                if(Lists.newArrayList(0,30).contains(i)){
                    Result<EntityYhMqtt0607> resultB =  this.emqxClientService.yhMqtt0607(yhMqtt0607Request);
                    log.info("log_4：发送洗衣机指令结果：【{}】",JSON.toJSONString(resultB));
                }
                Thread.sleep(20L);

            }
        }else if (entityMqttDevice.getMqttDeviceType().equals(2)){

            YhMqtt0606Request yhMqtt0606Request = new YhMqtt0606Request();
            yhMqtt0606Request.setDeviceNo(entityMqttDevice.getMqttDeviceNo());
            yhMqtt0606Request.setOrderNo(entityMqttOperationProcess.getOrderId().longValue());
//            yhMqtt0606Request.setTotalTime(Integer.parseInt(entityMqttOperationProcess.getOperateCode()));
            yhMqtt0606Request.setTotalTime(getInt(entityMqttOperationProcess.getOperateCode()));
            yhMqtt0606Request.setOverTime(new BigDecimal(2));

            log.info("发送吹风机06指令：【{}】",JSON.toJSONString(yhMqtt0606Request));
            for (int i=0;i<50;i++){
                status8A = (Integer) this.redisUtil.get("YH_"+ entityMqttDevice.getMqttDeviceNo() + "_run_8A");
                if(ObjectUtil.isNotEmpty(status8A)){
                    log.info("监测到存在8A数据：【{}】，退出循环",JSON.toJSONString(yhMqtt0606Request));
                    break;
                }
                status87 = (Integer) this.redisUtil.get("YH_"+entityMqttDevice.getMqttDeviceNo()+"_"+entityMqttOperationProcess.getOrderId()+"_87");
                if(ObjectUtil.isNotEmpty(status87)){
                    log.info("监测到存在87数据：【{}】，退出循环",JSON.toJSONString(yhMqtt0606Request));
                    break;
                }
                if(Lists.newArrayList(0,30).contains(i)){
                    this.emqxClientService.yhMqtt0606(yhMqtt0606Request);
                }
                Thread.sleep(20L);

            }

        }

        for (int i=0;i<50;i++) {
            status8A = (Integer) this.redisUtil.get("YH_" + entityMqttDevice.getMqttDeviceNo() + "_run_8A");
            if (ObjectUtil.isNotEmpty(status8A)) {
                break;
            }
            Thread.sleep(20);
        }
        log.info("获取到8A的值：{}",status8A);
        if(ObjectUtil.isNotEmpty(status8A)){
            entityMqttOperationProcess.setState(0);
            entityMqttOperationProcess.setBeginTime(new Date());
            entityMqttOperationProcess.setMqttDeviceSub(status8A.longValue());
            this.mqttOperationService.update(entityMqttOperationProcess.getComId(),entityMqttOperationProcess);
            EntityMqttOperation entityMqttOperation = Convert.convert(EntityMqttOperation.class,entityMqttOperationProcess);
            this.xfRecordFeign.saveOrUpdateMqttOperation(entityMqttOperation);

            RefreshMqttOrderStatusRequest refreshMqttOrderStatusRequest = new RefreshMqttOrderStatusRequest();
            refreshMqttOrderStatusRequest.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo());
            refreshMqttOrderStatusRequest.setComId(entityMqttDevice.getComId());
            refreshMqttOrderStatusRequest.setNewStatus(3);
            refreshMqttOrderStatusRequest.setNewSub(status8A);
            refreshMqttOrderStatusRequest.setSubRun(entityMqttDevice.getSubRun());
            this.refreshMqttOrderStatus(refreshMqttOrderStatusRequest);
            log.info("设备启动成功_1:{}",JSON.toJSONString(entityMqttDevice));
            resultmMap.put("runState",0);
            return ResultUtil.success(resultmMap);
//            return ResultUtil.success();
        }

        if(ObjectUtil.isNotEmpty(status87) && Objects.equals(status87, 0)){
            entityMqttOperationProcess.setState(31);
//            entityMqttOperationProcess.setBeginTime(new Date());
//            entityMqttOperationProcess.setMqttDeviceSub(status8A.longValue());
            this.mqttOperationService.update(entityMqttOperationProcess.getComId(),entityMqttOperationProcess);
            entityMqttOperationProcess.setState(0);
            entityMqttOperationProcess.setBeginTime(new Date());
            entityMqttOperationProcess.setMqttDeviceSub(status87.longValue());

            this.mqttOperationService.update(entityMqttOperationProcess.getComId(),entityMqttOperationProcess);
            EntityMqttOperation entityMqttOperation = Convert.convert(EntityMqttOperation.class,entityMqttOperationProcess);
            this.xfRecordFeign.saveOrUpdateMqttOperation(entityMqttOperation);

            RefreshMqttOrderStatusRequest refreshMqttOrderStatusRequest = new RefreshMqttOrderStatusRequest();
            refreshMqttOrderStatusRequest.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo());
            refreshMqttOrderStatusRequest.setComId(entityMqttDevice.getComId());
            refreshMqttOrderStatusRequest.setNewStatus(3);
            refreshMqttOrderStatusRequest.setNewSub(status87);
            refreshMqttOrderStatusRequest.setSubRun(entityMqttDevice.getSubRun());
            this.refreshMqttOrderStatus(refreshMqttOrderStatusRequest);
            log.info("设备启动成功_2");
            resultmMap.put("runState",0);
            return ResultUtil.success(resultmMap);
        }else{
            log.info("设备未能启动成功_1");
            resultmMap.put("runState",1);
            return ResultUtil.success(resultmMap);
//            return ResultUtil.error(ResultEnum.Err_6006);
        }
    }


    @PostMapping(PayConfigUrl.URL_refreshMqttOrderStatus)
    public Result refreshMqttOrderStatus(@RequestBody RefreshMqttOrderStatusRequest request){
        EntityMqttDevice entityMqttDevice = new EntityMqttDevice();
        entityMqttDevice.setMqttDeviceNo(request.getMqttDeviceNo());
//        entityMqttDevice.setOrderStatus(request.getNewStatus());
        entityMqttDevice.setComId(request.getComId());
        entityMqttDevice.setOrderTime(new Date());
        if(ObjectUtil.isNotEmpty(request.getNewSub())){
//            entityMqttDevice.setSubRun(request.getNewSub());
        }
        if(request.getNewStatus() < 3){
            entityMqttDevice.setOrderStatus(request.getNewStatus());
        }else if(request.getNewStatus() == 3){
            entityMqttDevice.setOrderStatus(0);
//            int newSub = 1 << request.getNewSub();
           int sub =  (int) Math.pow(2,request.getNewSub());
            int  newSub = request.getSubRun() | sub;
//            entityMqttDevice.setSubRun(newSub);
//            log.info("刷新状态_2：sub:{}====newSub:{},{}，{}",sub,newSub,JSON.toJSONString(request),JSON.toJSONString(entityMqttDevice));
        }else if(request.getNewStatus() == 4){

//            entityMqttDevice.setSubRun(request.get)
//            int newSub = 1 << request.getNewSub();
            entityMqttDevice.setOrderStatus(null);
            if(ObjectUtil.isEmpty(request.getSubRun())){
                request.setSubRun(0);
            }
//            int  newSub = request.getSubRun() & (~(int) Math.pow(2,request.getNewSub()));
//            entityMqttDevice.setSubRun(newSub);
//            log.info("刷新状态_3：{},{}",newSub,JSON.toJSONString(request));
        }
//        log.info("刷新状态_1：【{}】【{}】",JSON.toJSONString(request),JSON.toJSONString(entityMqttDevice));
        this.mqttDeviceService.update(request.getComId(), entityMqttDevice);

        this.redisUtil.hmSet("MqttXfDevice:" + entityMqttDevice.getMqttDeviceNo(), "orderStatus",entityMqttDevice.getOrderStatus());
        return ResultUtil.success();
    }

    //取消订单
    @PostMapping(PayConfigUrl.URL_cancelMqttOrder)
    public Result cancelMqttOrder(@RequestBody CancelMqttOrderRequest request){
        EntityMqttOperationProcess mqttOperationProcess = Convert.convert(EntityMqttOperationProcess.class,request);
        EntityMqttOperationProcess operationProcess = this.mqttOperationService.selectMqttProcess(request.getComId(),mqttOperationProcess, Lists.newArrayList(11,13));
        if(ObjectUtil.isEmpty(operationProcess)){
            return ResultUtil.error(ResultEnum.Err_6007);
        }

        operationProcess.setState(operationProcess.getState() - 30);
        this.mqttOperationService.update(mqttOperationProcess.getComId(),operationProcess);

        //刷新状态
        RefreshMqttOrderStatusRequest refreshMqttOrderStatusRequest = new RefreshMqttOrderStatusRequest();
        refreshMqttOrderStatusRequest.setMqttDeviceNo(operationProcess.getMqttDeviceNo());
        refreshMqttOrderStatusRequest.setNewStatus(0);
        refreshMqttOrderStatusRequest.setComId(operationProcess.getComId());
        this.refreshMqttOrderStatus(refreshMqttOrderStatusRequest);

        //退款
        InvalidMqttOrderRequest invalidMqttOrderRequest = new InvalidMqttOrderRequest();
        invalidMqttOrderRequest.setOrderNo(operationProcess.getOrderNo());
        invalidMqttOrderRequest.setComId(operationProcess.getComId());
        this.invalidMqttOrder(invalidMqttOrderRequest);
        return ResultUtil.success();
    }

    //超时管理
    @PostMapping(PayConfigUrl.URL_timerMqttOrder)
    public Result timerMqttOrder(@RequestBody TimerMqttOrderRequest request){
        if(Lists.newArrayList(11,13,31).contains(request.getOrderState())){
            log.info("====支付超时====");
            //支付超时
            List<EntityMqttOperationProcess> entityXfRecordProcessList = this.getTimerMqttOrder(request.getOrderState());
            for (EntityMqttOperationProcess entityMqttOperationProcess:entityXfRecordProcessList){
                entityMqttOperationProcess.setState(-request.getOrderState());
                entityMqttOperationProcess.setUpdateTime(new Date());
                //更新
                this.mqttOperationService.update(entityMqttOperationProcess.getComId(),entityMqttOperationProcess);

                //同步
                EntityMqttOperation entityMqttOperation = Convert.convert(EntityMqttOperation.class,entityMqttOperationProcess);
                this.xfRecordFeign.saveOrUpdateMqttOperation(entityMqttOperation);

                //更新状态
                RefreshMqttOrderStatusRequest refreshMqttOrderStatusRequest = new RefreshMqttOrderStatusRequest();
                refreshMqttOrderStatusRequest.setMqttDeviceNo(entityMqttOperation.getMqttDeviceNo());
                refreshMqttOrderStatusRequest.setNewStatus(0);
                refreshMqttOrderStatusRequest.setComId(entityMqttOperation.getComId());
                this.refreshMqttOrderStatus(refreshMqttOrderStatusRequest);

                //退款
                InvalidMqttOrderRequest invalidMqttOrderRequest = new InvalidMqttOrderRequest();
                invalidMqttOrderRequest.setOrderNo(entityMqttOperation.getOrderNo());
                invalidMqttOrderRequest.setComId(entityMqttOperation.getComId());
                this.invalidMqttOrder(invalidMqttOrderRequest);
            }
        }else if(Lists.newArrayList(0).contains(request.getOrderState())){
            //设备使用超时
            Result<List<EntityMqttOperation>> resultA = this.xfRecordFeign.timerMqttOrder(request);
            if(resultA.getCode() != 200 || ObjectUtil.isEmpty(resultA.getData())){
                return ResultUtil.success();
            }

            for(EntityMqttOperation entityMqttOperation: resultA.getData()){
                RefreshMqttOrderStatusRequest refreshMqttOrderStatusRequest = new RefreshMqttOrderStatusRequest();
                refreshMqttOrderStatusRequest.setMqttDeviceNo(entityMqttOperation.getMqttDeviceNo());
                refreshMqttOrderStatusRequest.setComId(entityMqttOperation.getComId());
                refreshMqttOrderStatusRequest.setNewStatus(4);
                this.refreshMqttOrderStatus(refreshMqttOrderStatusRequest);
            }

        }


        return ResultUtil.success();
    }

    private List<EntityMqttOperationProcess> getTimerMqttOrder(Integer orderState) {
        Integer sec = 600;
        if(orderState == 11){
            sec = 600;
        }else if(orderState == 13){
            sec = 120;
        }else if(orderState == 31){
            sec = 90;
        }
        List<EntityMqttOperationProcess> resultList = new ArrayList<>();
        List<EntityMqttOperationProcess> listA = this.mqttOperationService.getTimerMqttOrder(100L,orderState,sec);
        List<EntityMqttOperationProcess> listB = this.mqttOperationService.getTimerMqttOrder(600L,orderState,sec);
        if(ObjectUtil.isNotEmpty(listA)){
            resultList.addAll(listA);
        }

        if(ObjectUtil.isNotEmpty(listB)){
            if(ObjectUtil.isEmpty(resultList)){
                resultList.addAll(listB);
            }else{
                Map<Integer,Long> map = new HashMap<>();
                resultList.forEach(process -> {
                    map.put(process.getId(), process.getComId());
                });
//                for
                listB.forEach(process -> {
                    if(ObjectUtil.isEmpty(map.get(process.getId()))){
                        resultList.add(process);
                    }
                });
            }

        }

//        for (int i=0;i<2;i++){
//            Long companyId = i==0?1L:600L;
//            log.info("companyId：{}",companyId);
//
//            if(ObjectUtil.isNotEmpty(list)){
//                resultList.addAll(list);
//            }
//        }
        return resultList;
    }
    //
    @PostMapping(PayConfigUrl.URL_invalidMqttOrder)
    public Result invalidMqttOrder(@RequestBody InvalidMqttOrderRequest request){
        List<EntityXfRecordProcess> list =  this.xfRecordProcessService.selectPlatOrderNo(request.getComId(), request.getOrderNo());
        if(ObjectUtil.isEmpty(list)){
            return ResultUtil.success();
        }
        for(EntityXfRecordProcess process:list){
            if(!process.getPayState().equals(0)){
                return ResultUtil.success();
            }
        }

        //TODO MQ发起退款
        for (EntityXfRecordProcess entityXfRecordProcess:list){
            EntityXfRecordProcessExtend entityXfRecordProcessExtend = new EntityXfRecordProcessExtend();
            entityXfRecordProcessExtend.setOrderNo(entityXfRecordProcess.getOrderNo());
            entityXfRecordProcessExtend.setOrderId(entityXfRecordProcess.getId());
            entityXfRecordProcessExtend.setCancelState(1);
            entityXfRecordProcessExtend.setComId(entityXfRecordProcess.getComId());
            this.xfRecordProcessExtendService.saveOrUpdate(entityXfRecordProcess.getComId(),entityXfRecordProcessExtend);
//            QrCodeRefundRequest qrCodeRefundRequest = new QrCodeRefundRequest();
//            qrCodeRefundRequest.setRefundAmount(entityXfRecordProcess.getAmount());
//            qrCodeRefundRequest.setCompanyId(entityXfRecordProcess.getComId());
//            qrCodeRefundRequest.setMachNo(entityXfRecordProcess.getDeviceNo());
//            qrCodeRefundRequest.setTradeNo(entityXfRecordProcess.getOrderNo());
//            qrCodeRefundRequest.setOrigTradeNo(entityXfRecordProcess.getOrigOrderNo());
//            this.payhandleClientService.qrCodeRefund(qrCodeRefundRequest);
        }
        return ResultUtil.success();
    }

    /**
     * 设备停止工作
     * @param request
     * @return
     */
    @PostMapping(PayConfigUrl.URL_deviceStopWork)
    public Result deviceStopWork(@RequestBody DeviceStopWorkRequest request){
//        int powerOfTwo = 1 << request.getNewSub();
        int resultSub = request.getSubRun() & (~(int)Math.pow(2,request.getNewSub()));
        EntityMqttOperation entityMqttOperation = Convert.convert(EntityMqttOperation.class,request);
        Map<String,Integer> resultMap = new HashMap<>();
        Result<EntityMqttOperation>  result = this.xfRecordFeign.detailMqttOption(entityMqttOperation);
        if(result.getCode() != 200 || ObjectUtil.isEmpty(result.getData())){
            return ResultUtil.success(resultMap);
        }
        entityMqttOperation = result.getData();
        entityMqttOperation.setEndTime(new Date());
        this.xfRecordFeign.updateMqttOperation(entityMqttOperation);
        redisUtil.hmSet("MqttXfDevice:"+ request.getMqttDeviceNo(),"subRun",resultSub);
        return ResultUtil.success();

    }

    @PostMapping(PayConfigUrl.URL_deviceStartWork)
    public Result deviceStartWork(@RequestBody DeviceStartWorkRequest request){
        EntityMqttOperationProcess entityMqttOperationProcess = Convert.convert(EntityMqttOperationProcess.class,request);
//        entityMqttOperationProcess.setMqttDeviceSub(null);
        entityMqttOperationProcess = this.mqttOperationService.selectMqttProcess(request.getComId(), entityMqttOperationProcess);
        if(ObjectUtil.isEmpty(entityMqttOperationProcess)){
            log.info("设备启动失败：{}",JSON.toJSONString(request));
            return ResultUtil.success();
        }

//        int powerOfTwo = 1 << request.getMqttDeviceSub();
        int resultSub = request.getSubRun();
        entityMqttOperationProcess.setState(0);
        entityMqttOperationProcess.setBeginTime(new Date());
        entityMqttOperationProcess.setMqttDeviceSub((long) resultSub);
        this.mqttOperationService.update(request.getComId(),entityMqttOperationProcess);
        EntityMqttOperation entityMqttOperation = Convert.convert(EntityMqttOperation.class,entityMqttOperationProcess);
        this.xfRecordFeign.saveOrUpdateMqttOperation(entityMqttOperation);
        redisUtil.hmSet("MqttXfDevice:"+ request.getMqttDeviceNo(),"subRun",resultSub);
        redisUtil.hmSet("MqttXfDevice:"+ request.getMqttDeviceNo(),"orderStatus",0);

        return ResultUtil.success();
    }


    @PostMapping(PayConfigUrl.URL_selectDeviceOne)
    public Result selectDeviceOne(@RequestBody EntityMqttDevice device){
        return ResultUtil.success(this.mqttDeviceService.selectDevice(device.getComId(), device));
    }

    public static Integer getInt(String string){
        String numbers = string.replaceAll("\\D+", "");
        return Integer.parseInt(numbers.trim());
    }
    /**
     * 十进制转16进制，并补零
     * @param para 十进制参数
     * @param length 需要的位数长度
     * @return
     */
    public static String intToHexWithFillZero(int para,int length){
        int requiredLength = 2 * length; // 需要两位十六进制数
        return String.format("%0" + requiredLength + "X", para).toUpperCase();
    }

    //平方取反(按位与按位取反2的@newSub次方)
    public static Integer getSubRunB(Integer subRun){
        subRun  = ObjectUtil.isEmpty(subRun)?0:subRun;
        return subRun & (~(int)Math.pow(2,subRun));
    }

    //按位或2的@newSub次方
    public static Integer getSubRunA(Integer subRun){
        subRun  = ObjectUtil.isEmpty(subRun)?0:subRun;
        return subRun | ((int)Math.pow(2,subRun));
    }

    public DeviceInfoVo getDeviceInfo(@RequestBody GetDeviceInfoRequest getDeviceInfoRequest){
//        Long timeLong= (long) (4 * 60 * 60);
//        //查询redis是否为空，不为空把值存入redis
//        String deviceInfoVoRedis="xf_device_info#comId:"+getDeviceInfoRequest.getComId()+"#machNo:"+getDeviceInfoRequest.getMachNo()+"#";
//        Object objectDeviceInfo=redisUtil.get(deviceInfoVoRedis);
//        DeviceInfoVo deviceInfoVo=null;
//        if (objectDeviceInfo == null) {
//            deviceInfoVo=this.mqttDeviceService.selectPointId(getDeviceInfoRequest.getComId(),getDeviceInfoRequest.getMachNo());
//            if (deviceInfoVo!=null){
//                redisUtil.set(deviceInfoVoRedis, deviceInfoVo,timeLong);
//            }
//        }else {
//            deviceInfoVo = JSON.parseObject(JSON.toJSONString(objectDeviceInfo), DeviceInfoVo.class);
//        }
        DeviceInfoVo deviceInfoVo=this.mqttDeviceService.selectPointId(getDeviceInfoRequest.getComId(),getDeviceInfoRequest.getMachNo());
        return deviceInfoVo;
    }
}
